<?php

namespace app\api\controller\user;

use app\api\controller\AuthController;
use app\api\service\BalanceService;
use app\api\service\GoldService;

class BalanceController extends AuthController
{
    /**
     * 金豆兑换余额
     * */
    public function redeem()
    {
        $param = $this->request->param();

        if (empty($param['store_id']) || empty($param['gold_num'])){
            return json(['code' =>0, 'msg' => '参数非法!']);
        }

        $balance_scale = BalanceService::getBalanceRedeemScale($param['store_id']);

        $user_id = $this->request->user['user_id'];

        $user_gold = GoldService::getUserGold($user_id);



        if ($param['gold_num']>$user_gold){
            return json(['code' =>0, 'msg' => '金豆不足,兑换失败!']);
        }

        (float)$balance = $param['gold_num']*$balance_scale;




        $result =  BalanceService::reedBanlance($user_id,$param['gold_num'],$balance);

        return  $result ? json(['code' =>1, 'msg' => '兑换成功!']) : json(['code' =>0, 'msg' => '兑换失败!']);


    }
}